import base64
import numpy as np
import cv2
from PIL import Image
import io

def base2numpy(base):
  img_bin = base64.b64decode(base.split(';base64,')[-1])
  img_buff = np.frombuffer(img_bin, dtype='uint8')
  image = cv2.imdecode(img_buff, 1)
  return image

def base2bytes(base):
  img_bin = base64.b64decode(base.split(';base64,')[-1])
  return img_bin

def file2base64(file_path):
  with open(file_path, "rb") as file:
    encoded_string = base64.b64encode(file.read())
  return encoded_string.decode("utf-8")

def base2file(file_path, base):
  img_bin = base64.b64decode(base.split(';base64,')[-1])
  with open(file_path, "wb") as file:
    file.write(img_bin)

def bytes2PIL(img_bin) -> Image:
  image = Image.open(io.BytesIO(img_bin))
  return image

def base642PIL(base) -> Image:
  img_bin = base64.b64decode(base.split(';base64,')[-1])
  image = Image.open(io.BytesIO(img_bin))
  return image

def PIL2base64(image, format ="JPEG", dpi = (300, 300), quality=100) -> str:
  image.info['dpi'] = dpi
  byte_io = io.BytesIO()
  # subsampling=0 480*640 会导致图片超过300kb，如果不设置，则在200左右
  # image.save(byte_io, format=format, dpi=dpi, quality=quality, subsampling=0)
  image.save(byte_io, format=format, dpi=dpi, quality=quality)
  byte_data = byte_io.getvalue()
  # 将byte流编码为base64字符串
  base64_str = base64.b64encode(byte_data).decode('utf-8')
  # 将图像转换为byte流
  return base64_str

def hex_to_rgb(hex_code):
  return tuple(int(hex_code.lstrip('#')[i:i + 2], 16) for i in range(0, 6, 2))

def orientation(image):
  try:
    exif = image._getexif()
  except AttributeError:
    exif = None
  if exif:
    orientation = exif.get(0x0112)
    if orientation == 2:
      image = image.transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 3:
      image = image.transpose(Image.ROTATE_180)
    elif orientation == 4:
      image = image.transpose(Image.FLIP_TOP_BOTTOM)
    elif orientation == 5:
     image = image.transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 6:
     image = image.transpose(Image.ROTATE_270)
    elif orientation == 7:
     image = image.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 8:
      image = image.transpose(Image.ROTATE_90)
  return image
